/*
 * Copyright (C) 2011 Young,Fey <fey.young@gmail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package com.youngfey.sqlite
import groovy.transform.*

/**
 * 用于表述数据行
 * @author Young,Fey <fey.young@gmail.com>
 */
class Row extends Expando {
    /**
     * @param maps 待转换的行集合，要求每一个成员（map）的键在转换为字符串
     * 后均符合SQLite对Column Name的约束。各map的键无需统一，键值文本相同的
     * map其值无需统一类型
     * @return 转换后的行集合
     */
    static List<Row> getInstances(List<Map> maps) {
        maps.collect { new Row(it) }
    }

    /**
     * 根据Map内容构造新Row对象
     */
    def Row(Map map) {
        map.each { k, v -> putAt(k, v) }
    }

    /**
     * 便捷方法，使Row可以像Map一样支持get操作
     */
    def get(obj) {
        obj == null ? null : getAt(obj)
    }

    /**
     * 便捷方法，使Row可以像Map一样支持put操作
     * @return put操作前指定键值的值
     */
    def put(key, value) {
        def old = get(key)
        putAt key, value
        old
    }

    /**
     * @return 返回对应Row的数据内容的Map
     */
    Map toMap() {
        properties
    }

    /**
     * @return 返回Row对应的Map数据，但剔除未包含在Columns中的键组
     */
    Map toMap(Map<String, Column> columns) {
        properties.findAll { columns.containsKey(it.key) }
    }

    /**
     * @return 返回该行所具有的所有值域
     */
    Set<String> getFields() {
        properties.keySet()
    }

    @Override
    String toString() {
        toMap().collect { k, v -> "$k = $v" }.join(', ')
    }
}
